package cn.tedu.csmall.order.webapi.service.impl;

import cn.tedu.csmall.cart.service.ICartService;
import cn.tedu.csmall.commons.pojo.order.dto.OrderAddDTO;
import cn.tedu.csmall.commons.pojo.order.vo.OrderTbl;
import cn.tedu.csmall.commons.pojo.stock.dto.StockReduceCountDTO;
import cn.tedu.csmall.commons.restful.JsonPage;
import cn.tedu.csmall.order.webapi.mapper.OrderMapper;
import cn.tedu.csmall.order.service.IOrderService;
import cn.tedu.csmall.stock.service.IStockService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@DubboService
@Service
@Slf4j
public class OrderServiceImpl implements IOrderService {
    @Autowired
    private OrderMapper orderMapper;
    // 要想使用dubbo调用远程模块，需要@DubboReference注解，否则无法获取到业务逻辑层实现类对象
    @DubboReference
    private IStockService dubboStockService;
    @DubboReference
    private ICartService dubboCartService;
    @Override
    public void orderAdd(OrderAddDTO orderAddDTO) {
        //TODO:1.减少库存--调用stock模块
        StockReduceCountDTO stockReduceCountDTO = new StockReduceCountDTO();
        stockReduceCountDTO.setCommodityCode(orderAddDTO.getCommodityCode());
        stockReduceCountDTO.setReduceCount(orderAddDTO.getCount());
        dubboStockService.reduceCountByCommodityCode(stockReduceCountDTO);
        //TODO:2.删除购物车中选择的商品--调用cart模块
        dubboCartService.deleteUserCart(orderAddDTO.getUserId(),orderAddDTO.getCommodityCode());
        //3.新增订单
        OrderTbl order = new OrderTbl();
        BeanUtils.copyProperties(orderAddDTO,order);
        //执行新增
        orderMapper.insertOrder(order);
        log.info("新增的订单信息为：{}",order);
    }

    //分页查询
    //pageNum页码，pageSize每页条数
    public JsonPage<OrderTbl> getAllOrdersByPage(Integer pageNum, Integer pageSize){
        //要用PageHelper实现分页查询
        //需要设置分页条件，页码1就是1 、每页条数
        PageHelper.startPage(pageNum,pageSize);
        //下面运行查询语句，会在自动末尾添加limit，不要人为计算
        List<OrderTbl> allOrders = orderMapper.findAllOrders();
        //上面查询结果就是分页结果，List集合中只有指定的页面的苏韩剧，并不是全查
        //如果想要包含分页信息，PageHelper提供的PageInfo中就有
        return JsonPage.restPage(new PageInfo<>(allOrders));
    }
}
